﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Devfw.OpenAuth;
using System.Net;
using Devfw;

namespace Devfw.OpenAuth.Platform
{
    public class TencentV2 : Provider20Base
    {
        string _openid = string.Empty;
        public TencentV2(string apiKey, string secretKey)
            : base(apiKey, secretKey)
        { }
        public TencentV2(string apiKey, string secretKey, string accessToken, string refreshToken,string openid)
            : base(apiKey, secretKey, accessToken, refreshToken)
        {
            _openid = openid;
        }

        #region 认证

        private const string authorizeUrl = "https://graph.qq.com/oauth2.0/authorize"; // "https://open.t.qq.com/cgi-bin/oauth2/authorize";
        private const string accesstokenUrl = "https://graph.qq.com/oauth2.0/token"; //"https://open.t.qq.com/cgi-bin/oauth2/access_token";


        public override string authorize()
        {
            return string.Empty;
        }

        /// <summary>
        /// 用来换取accesstoken的授权码，有效期为10分钟
        /// </summary>
        /// <param name="state"></param>
        /// <returns></returns>
        public string GetAuthorizeUrl(string callback)
        {
            string query = string.Format( "response_type=code&client_id={0}&redirect_uri={1}&state=test", APIKey, HttpUtility.UrlEncode( callback ) );
            return OpenAuthHelper.CombinUrl(authorizeUrl, query);
        }

        /// <summary>
        /// accesstoken过期时间应用级别: accesstoken有效期 
        ///初级: 7天 
        ///高级: 15天 
        ///腾讯合作方: 30天 
        /// </summary>
        /// <param name="authorization_code"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public override string getAccessToken(string authorization_code, string callback)
        {
            string query = string.Format( "grant_type=authorization_code&client_id={1}&client_secret={2}&code={0}&state=test&redirect_uri={3}", authorization_code, APIKey, SecretKey, HttpUtility.UrlEncode( callback ) );
            string response = OpenAuthHelper.WebRequest(HttpWebMethod.GET, OpenAuthHelper.CombinUrl(accesstokenUrl, query), string.Empty, string.Empty);

            return response;
        }

        public override string getRefreshToken()
        {
            string query = string.Format("grant_type=refresh_token&refresh_token={0}&client_id={1}&client_secret={2}", RefreshToken, APIKey, SecretKey);
            string response = OpenAuthHelper.WebRequest(HttpWebMethod.POST, OpenAuthHelper.CombinUrl(accesstokenUrl, query), string.Empty, string.Empty);
            return response;
        }


        #endregion 认证


        public string t_get(string format, string blogID)
        {
            string response = WebRequest(HttpWebMethod.POST, "https://open.t.qq.com/api/t/show",
               new ParameterCollection()
                {
                    new Parameter("format", format, ParameterType.Get),
                    new Parameter("id", blogID, ParameterType.Get)
                });
            return response;
        }

        public string t_add(string format, string content, string clienIP)
        {
            // _core.AuthorizationType = AuthorizationType.PostRequestBody;
            string response = WebRequest(HttpWebMethod.POST, "https://open.t.qq.com/api/t/add",
                new ParameterCollection()
                {
                    new Parameter("format", format, ParameterType.Post),
                    new Parameter("content", content, ParameterType.Post),
                    new Parameter("clientip", HttpUtility.UrlEncode( clienIP ), ParameterType.Post),
                });
            return response;
        }

        public string t_add_pic(string format, string content, string clienIP, byte[] imageByte, string fileName)
        {
            // _core.AuthorizationType = AuthorizationType.PostRequestBody;
            var contentEncoding = "iso-8859-1";
            string fileData = System.Text.Encoding.GetEncoding(contentEncoding).GetString(imageByte);
            // string fileData = System.Text.Encoding.ASCII.GetString( imageByte );

            //_core.AuthorizationType = AuthorizationType.FormDataPost;
            string response = WebRequest(HttpWebMethod.POST, "https://open.t.qq.com/api/t/add_pic",
                new ParameterCollection()
                {
                    new PostParameter("format", format ),
                    new PostParameter("content", content),
                    new PostParameter("jing", ""),
                    new PostParameter("wei", ""),
                    new PostParameter("clientip", clienIP),
                    // new PostParameter( "pic", fileData, "utf-8", "application/octet-stream", "binary", "filename=\"" + fileName + "\"", false )
                    new PostParameter( "pic", fileData, true, "filename=\"" + fileName + "\"", false )
                });
            return response;
        }

        public string t_add_pic(string format, string content, string clienIP, string url)
        {
            WebClient client = new WebClient();
            byte[] b = client.DownloadData(url);
            string[] f = url.Split('\\', '/');
            return t_add_pic(format, content, clienIP, b, f[f.Length - 1]);
        }

        public string get_other_info(string fopenID, string name)
        {
            string response = WebRequest(HttpWebMethod.POST, "https://open.t.qq.com/api/user/other_info",
                new ParameterCollection()
                {
                    
                    new Parameter( "format", "xml", ParameterType.Get ),
                    new Parameter( "name", name , ParameterType.Get ),
                    new Parameter( "fopenid", fopenID , ParameterType.Get )
                    
                });

            return response;
        }

        public string StatusesRepost(string content, string id, string clientip)
        {
            return StatusesRepost(content, id, clientip, "", "");
        }
        public string StatusesRepost(string content, string id, string clientip, string jing, string wei)
        {
            string response = WebRequest(HttpWebMethod.POST, "https://open.t.qq.com/api/t/re_add",
                new ParameterCollection()
                {
                    
                    new Parameter( "format", "xml", ParameterType.Post ),
                    new Parameter( "content", content , ParameterType.Post ),
                    new Parameter( "clientip", HttpUtility.UrlEncode(clientip) , ParameterType.Post ),
                    new Parameter( "jing", jing , ParameterType.Post ),
                    new Parameter( "wei", wei , ParameterType.Post ),
                    new Parameter( "reid", id , ParameterType.Post )
                });

            return response;
        }


        public string StatusesComment(string content, string id, string clientip)
        {
            return StatusesComment(content, id, clientip, "", "");
        }

        public string StatusesComment(string content, string id, string clientip, string jing, string wei)
        {
            string response = WebRequest(HttpWebMethod.POST, "https://open.t.qq.com/api/t/comment",
                new ParameterCollection()
                {
                    new Parameter( "format", "xml", ParameterType.Post ),
                    new Parameter( "content", content , ParameterType.Post ),
                    new Parameter( "Clientip", HttpUtility.UrlEncode(clientip) , ParameterType.Post ),
                    new Parameter( "jing", jing , ParameterType.Post ),
                    new Parameter( "wei", wei , ParameterType.Post ),
                    new Parameter( "reid", id , ParameterType.Post )
                });

            return response;

        }

        public string getFanslist(string reqnum, string startindex)
        {
            return getFriendlist("https://open.t.qq.com/api/friends/fanslist", reqnum, startindex);
        }

        public string getIdollist(string reqnum, string startindex)
        {
            return getFriendlist("https://open.t.qq.com/api/friends/idollist", reqnum, startindex);
        }

        public string getFriendlist(string url, string reqnum, string startindex)
        {
            string response = WebRequest(HttpWebMethod.GET, url,
                new ParameterCollection()
                {
                    
                    new Parameter( "format", "xml", ParameterType.Get ),
                    new Parameter( "reqnum", reqnum , ParameterType.Get ),
                    new Parameter( "startindex", startindex , ParameterType.Get )
                    
                });

            return response;
        }

        public string getUserShow()
        {
            string response = WebRequest(HttpWebMethod.POST, "https://open.t.qq.com/api/user/info",
                new ParameterCollection()
                {
                    
                    new Parameter( "format", "xml", ParameterType.Get )
                    
                });

            return response;
        }

        public string setSetFriendship(string acttype, string id)
        {

            string response = WebRequest(HttpWebMethod.POST, string.Format("https://open.t.qq.com/api/friends/{0}", acttype),
                new ParameterCollection()
                {
                    new Parameter( "format", "xml", ParameterType.Post ),
                    new Parameter( "name", id, ParameterType.Post )
                });

            return response;
        }

        public string addFriends(string[] fopenids)
        {
            string response = WebRequest(HttpWebMethod.POST, "https://open.t.qq.com/api/friends/add",
                new ParameterCollection()
                {
                    
                    new Parameter( "format", "xml", ParameterType.Post ),
                    new Parameter( "fopenids",string.Join( "_", fopenids ) , ParameterType.Post )
                    
                });

            return response;
        }

        public string addFriend(string fopenid)
        {
            return addFriends(new string[] { fopenid });
        }

        public string removeFriend(string fopenid)
        {
            string response = WebRequest(HttpWebMethod.POST, "https://open.t.qq.com/api/friends/del",
                new ParameterCollection()
                {
                    
                    new Parameter( "format", "xml", ParameterType.Post ),
                    new Parameter( "fopenid",fopenid , ParameterType.Post )
                    
                });

            return response;
        }




        public string WebRequest(HttpWebMethod httpWebMethod, string url, ParameterCollection collect)
        {
            collect.Add(new Parameter("oauth_consumer_key", APIKey, ParameterType.Get));
            collect.Add(new Parameter("openid", _openid, ParameterType.Get));
            collect.Add(new Parameter("oauth_version", "2.a", ParameterType.Get));
            collect.Add(new Parameter("scope", "all", ParameterType.Get));
            collect.Add(new Parameter("access_token", AccessToken, ParameterType.Get));
            string querypost = OpenAuthHelper.ToQueryString(collect.GetParameters(ParameterType.Post));
            string queryget = OpenAuthHelper.ToQueryString(collect.GetParameters(ParameterType.Get));
            string response = OpenAuthHelper.WebRequest(httpWebMethod, OpenAuthHelper.CombinUrl(url, queryget), querypost, string.Empty);
            return response;
        }
    }
}
